<template>
  <div>
    <div>
      <!--    搜索框-->
      <div class="mt-4">
        <el-input
            v-model="input"
            placeholder="在此输入想查询的信息"
            class="input-with-select"
            @input="filterSearch"
        >
          <template #prepend>
            <el-select v-model="select" placeholder="选择" style="width: 115px">
              <el-option label="姓名" value="1" />
              <el-option label="联系方式" value="2" />
              <el-option label="编号" value="3" />
              <el-option label="在职状态" value="4" />
            </el-select>
          </template>
          <template #append>
            <el-button :icon="Search" />
          </template>
        </el-input>

        <el-button type="primary" :icon="FolderChecked" @click="handleExcel"
                   style="margin-left: 20px;">导出员工excel
        </el-button>
      </div>
    </div>
    <!--    表格-->
    <el-table
        ref="tableRef"
        row-key="staffid"
        :data="tableData"
        style="width: 100%"
        @sort-change="handleSortChange"
        empty-text="暂无数据"
        @selection-change="handleSelectionChange"
    >
      <!--      编号列-->
      <el-table-column prop="staffid" label="编号" width="100" sortable></el-table-column>
      <!--      生日列-->
      <el-table-column
          prop="birthday"
          label="生日"
          sortable
          width="200"
          column-key="birthday"
          :formatter="formatTime"
      />
      <!--      姓名列-->
      <el-table-column prop="name" label="姓名" width="200" />
      <!--      联系方式列-->
      <el-table-column prop="phonenumber" label="联系方式" width="200" />
      <!--      性别列-->
      <el-table-column
          prop="gender"
          label="性别"
          width="100"
      >
        <template #default="scope">
          {{ scope.row.gender === 'F' ? '女' : '男' }}
        </template>
      </el-table-column>
      <!--      在职状态列-->
      <el-table-column
          prop="status"
          label="在职状态"
          width="100"
      >
        <template #default="scope">
          <el-tag
              :type="scope.row.status === 1 ? 'success' : 'info'"
              disable-transitions
          >{{ scope.row.status === 1 ? '在职' : '离职' }}</el-tag
          >
        </template>
      </el-table-column>
      <!--      编辑列-->
      <el-table-column label="操作">
        <template #default="scope">
          <el-button
              size="small"
              @click="handleEdit(scope.row)"
          >编辑</el-button
          >
        </template>
      </el-table-column>
    </el-table>
    <!--    分页功能-->
    <div class="demo-pagination-block">
      <el-pagination
          v-model:current-page="currentPage"
          :page-size="pageSize"
          background
          layout="total, prev, pager, next"
          :total="total"
          @current-change="handleCurrentChange"
      />
    </div>
    <!--表单数据-->
    <el-dialog v-model="dialogFormVisible" :title="dialogTitle" style="width: 400px">
      <el-form :model="tableform">
        <!--        姓名-->
        <el-form-item label="姓名">
          <el-input v-model="tableform.name" />
        </el-form-item>
        <!--        生日-->
        <el-form-item label="生日">
          <el-date-picker
              v-model="tableform.birthday"
              type="datetime"
              placeholder="选择日期"
              format="YYYY-MM-DD HH:mm:ss"
              value-format="YYYY-MM-DDTHH:mm:ss"
              style="width: 330px"
          />
        </el-form-item>
        <!--          联系方式-->
        <el-form-item label="联系方式">
          <el-input v-model="tableform.phonenumber" />
        </el-form-item>
        <!--        性别-->
        <el-form-item label="性别">
          <el-radio-group v-model="tableform.gender" style="margin-left: 28px">
            <el-radio :label="'M'">男</el-radio>
            <el-radio :label="'F'">女</el-radio>
          </el-radio-group>
        </el-form-item>
        <!--        在职状态-->
        <el-form-item label="在职状态">
          <el-radio-group v-model="tableform.status">
            <el-radio :label="1">在职</el-radio>
            <el-radio :label="0">离职</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="onSubmit" style="margin-left: 150px">确定</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import {onMounted, ref} from 'vue'
import {  FolderChecked, FolderAdd, Search } from '@element-plus/icons-vue'
import type { TableColumnCtx, TableInstance } from 'element-plus'
import { reactive,computed } from "vue";
import {ElMessage, genFileId, ElMessageBox} from "element-plus";
import axios from "axios";

interface User {
  staffid: number
  birthday: string
  name: string
  phonenumber: string
  gender: string
  status: number
}

//表格数据
const tableData = ref([])
let currentPage = ref(1); //定义当前页码初始值为1
const pageSize = ref(12); //定义每页显示的数据条数为5
let total = ref(0); //初始化数据总条数

// 格式化时间
const formatTime = (row) => {
  const date = new Date(row.birthday);
  const year = date.getFullYear();
  const month = ("0" + (date.getMonth() + 1)).slice(-2);
  const day = ("0" + date.getDate()).slice(-2);
  const hour = ("0" + date.getHours()).slice(-2);
  const minute = ("0" + date.getMinutes()).slice(-2);
  const seconds = ("0" + date.getSeconds()).slice(-2);
  return `${year}-${month}-${day} ${hour}:${minute}:${seconds}`;
}

// 使用axios.get()方法获取用户列表
// 在组件挂载后执行回调函数
onMounted(() => {
  getData()
})

// 获取当前页数据
const getData = () => {
  axios.get("http://192.168.166.182:8080/staff/getAllStaffs",{
    params: {
      pageNo: currentPage.value,
      pageSize: pageSize.value
    }
  }).then(response => {
    console.log(response.data)
    tableData.value  = response.data.records;
    total.value = response.data.total;
  }).catch(error => {
    console.error(error);
  })
}

//页数改变
const handleCurrentChange = (newPage) => {
  currentPage.value = newPage;
  getData();
}

//排序
const handleSortChange = (sortData) => {
  //解构sortData参数，得到prop和order两个属性
  const { prop,order } = sortData;
  //使用sort方法对当前页面数据进行排序，并更新其值
  tableData.value = tableData.value.sort((a,b) => {
    if(order === 'ascending') { //升序
      return a[prop] === b[prop] ? a.staffid - b.staffid : a[prop] > b[prop] ? 1 : -1;
    } else { //降序
      return a[prop] === b[prop] ? a.staffid - b.staffid : a[prop] < b[prop] ? 1 : -1;
    }
  });
}

const input = ref('') //初始化搜索输入框
const select = ref('') //初始化搜索选择栏
//搜索框搜查
const filterSearch = (val) => {
  //根据姓名搜索
  if(select.value === "1") {
    //搜索框有输入
    if(val.length > 0) {
      axios.get(`http://192.168.166.182:8080/staff/selectByName`,{
        params: {
          name: val,
          pageNo: currentPage.value,
          pageSize: pageSize.value
        }
      }).then(response => {
        console.log(response.data)
        tableData.value = response.data.records;
        total.value = response.data.total;
      }).catch(error => {
        console.error(error)
      })
    } else { //搜索框无输入
      getData(); //还原表格数据
    }
  } else if(select.value === "2") { //根据联系方式搜索
    //搜索框有输入
    if(val.length > 0) {
      axios.get(`http://192.168.166.182:8080/staff/selectByPhone`,{
        params: {
          phone: val,
          pageNo: currentPage.value,
          pageSize: pageSize.value
        }
      }).then(response => {
        console.log(response.data)
        tableData.value = response.data.records;
        total.value = response.data.total;
      }).catch(error => {
        console.error(error)
      })
    } else { //搜索框无输入
      getData();
    }
  }else if(select.value === "3") { // 根据编号搜索
    if(val.length > 0) {
      axios.get(`http://192.168.166.182:8080/staff/selectById`,{
        params: {
          id: val,
          pageNo: currentPage.value,
          pageSize: pageSize.value
        }
      }).then(response => {
        console.log(response.data)
        tableData.value = response.data.records;
        total.value = response.data.total;
      }).catch(error => {
        console.error(error)
      })
    } else {
      getData();
    }
  } else if(select.value === "4") { // 根据在职状态搜索
    if(val.length > 0) {
      const status = ref();
      if(val === '离职') status.value = 0;
      else status.value = 1;
      axios.get(`http://192.168.166.182:8080/staff/selectByStatus`,{
        params: {
          status: status.value,
          pageNo: currentPage.value,
          pageSize: pageSize.value
        }
      }).then(response => {
        console.log(response.data)
        tableData.value = response.data.records;
        total.value = response.data.total;
      }).catch(error => {
        console.error(error)
      })
    } else {
      getData();
    }
  }
}

const dialogFormVisible = ref(false); //初始化弹窗不显示
let tableform = ref({}); //初始化弹窗表单数据
const dialogTitle = ( '编辑数据'); // 标题

//编辑数据按钮事件
const handleEdit = (row) => { //row为当前行的数据
  dialogFormVisible.value = true;
  tableform.value = {...row};
}

//确定添加数据
const onSubmit = () => {
  dialogFormVisible.value = false;
  // 创建一个副本来保存更新后的用户信息
  const updateMember = {...tableform.value}
  console.log(updateMember)
  // 发送 HTTP PUT 请求来更新用户信息
  axios.post(`http://192.168.166.182:8080/staff/change`,updateMember)
      .then(reponse => {
        // 处理成功响应
        ElMessage({type:'success',message:'修改成功！'})
        // 重新获取数据，更新表格显示
        getData()
      }).catch(error => {
    // 处理错误
    console.error('更新失败！')
    console.error(error)
  })
}

// excel导出
//导出为excel
const handleExcel = () =>{
  var url = "http://192.168.166.182:8080/staff/getStaffsExcel";
  axios({
    method: 'get',
    url: url,

    responseType: 'blob'
  })
      // axios.get('http://192.168.140.182:8080/student/getExcel')
      .then(res => {
        console.log(res)
        // const link = document.createElement("a");
        // const blob = new Blob([res], {
        //   type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8",
        // });
        // link.style.display = "none";
        // link.href = URL.createObjectURL(blob);
        // link.setAttribute("download", `学生数据.xlsx`);
        // document.body.appendChild(link);
        // link.click();
        // document.body.removeChild(link);
        const content = res.data
        const blob = new Blob([content], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' })
        const fileName = '员工数据.xlsx'
        if ('download' in document.createElement('a')) { // 非IE下载
          const elink = document.createElement('a')
          elink.download = fileName
          elink.style.display = 'none'
          elink.href = URL.createObjectURL(blob)
          document.body.appendChild(elink)
          elink.click()
          URL.revokeObjectURL(elink.href) // 释放URL 对象
          document.body.removeChild(elink)
        } else { // IE10+下载
          navigator.msSaveBlob(blob, fileName)
        }

      })
      .catch(error => {
        console.error(error);
      });
}

</script>

<style>
.input-with-select .el-input-group__prepend {
  background-color: var(--el-fill-color-blank);
}
.demo-pagination-block {
  margin-top: 10px;
}
.mt-4 {
  display: flex;
  justify-content: space-between;
  margin-bottom: 5px;
}
.bt1 {
  margin-left: 15px;
}
</style>
